#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int turn = 0;

void* handler1(void* arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (turn != 0)
        {
            pthread_cond_wait(&cond, &mutex);
        }
        cout << "我是线程A" << endl;
        turn = 1;
        pthread_cond_signal(&cond); // 通知线程B
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

void* handler2(void* arg)
{
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (turn != 1)
        {
            pthread_cond_wait(&cond, &mutex);
        }
        cout << "我是线程B" << endl;
        sleep(1);
        turn = 0;
        pthread_cond_signal(&cond); // 通知线程A
        pthread_mutex_unlock(&mutex);
    }
    return nullptr;
}

int main()
{
    pthread_t thread1, thread2;
    pthread_create(&thread1, nullptr, handler1, nullptr);
    pthread_create(&thread2, nullptr, handler2, nullptr);

    pthread_join(thread1, nullptr);
    pthread_join(thread2, nullptr);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    return 0;
}